package cn.tedu._07weibopjt.controller;

import cn.tedu._07weibopjt.base.response.JsonResult;
import cn.tedu._07weibopjt.base.utils.CacheUtil;
import cn.tedu._07weibopjt.mapper.WeiboMapper;
import cn.tedu._07weibopjt.pojo.dto.WeiboDTO;
import cn.tedu._07weibopjt.pojo.entity.Weibo;
import cn.tedu._07weibopjt.pojo.vo.UserVO;
import cn.tedu._07weibopjt.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;

import static cn.tedu._07weibopjt.base.response.StatusCode.USER_NOT_LOGIN;

@RestController
@RequestMapping("/v1/weibo")
@Api(tags = "微博模块")
@Validated
@Slf4j

public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    @PostMapping("/insert")
    @ApiOperation("发布微博")
    public JsonResult insertWeibo(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO, weibo);
        weibo.setCreated(new java.util.Date());
        weibo.setUserId(userVO.getId());
        return JsonResult.ok(weiboMapper.insertWeibo(weibo));
    }

    @Autowired
    private CacheUtil cacheUtil;
    @GetMapping("/selectIndex")
    @ApiOperation("查询微博列表")
    public JsonResult selectIndex() {
        Serializable indexCache = cacheUtil.get("index_cache");
        log.debug("查询微博列表，缓存结果redis：{}", indexCache);
        if (indexCache == null) {
            List<WeiboIndexVO> weiboIndexVOS = weiboMapper.selectIndex();
            cacheUtil.setExp("index_cache", (Serializable) weiboIndexVOS,30);
            log.debug("查询微博列表，缓存结果mysql：{}", weiboIndexVOS);
            return JsonResult.ok(weiboIndexVOS);
        }
        return JsonResult.ok(indexCache);
    }

    @GetMapping("/selectById")
    @ApiOperation("查询微博详情")
    @ApiImplicitParam(name = "id", value = "微博id", required = true, dataType = "Long")
    public JsonResult selectById(@Range(min = 200, message = "微博id必须大于200") @RequestParam Long id) {
        return JsonResult.ok(weiboMapper.selectById(id));
    }
}
